package com.hotel.couponsystem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

//import com.hotel.config.AliyunPhoneConfig;
import com.hotel.config.aliyun.AliyunPhoneConfig;
import com.hotel.couponsystem.mapper.CouponAdminMapper;
import com.hotel.couponsystem.pojo.CouponAdmin;
import com.hotel.couponsystem.pojo.vo.CouponAdminVo;
import com.hotel.couponsystem.service.CouponAdminService;
import com.hotel.utils.UUIDUtils;
import com.hotel.utils.jwt.JwtUtil;
import com.hotel.websocketsystem.mapper.CustomerServiceUserMapper;
import com.hotel.websocketsystem.pojo.CustomerServiceUser;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * (CouponAdmin)表服务实现类
 *
 * @author makejava
 * @since 2022-09-30 15:01:30
 */
@Service("couponAdminService")
public class CouponAdminServiceImpl extends ServiceImpl<CouponAdminMapper, CouponAdmin> implements CouponAdminService {
    @Resource
    private CouponAdminMapper  couponAdminMapper;
    @Resource
    private AliyunPhoneConfig aliyunPhoneConfig;
    @Resource
    private CustomerServiceUserMapper customerServiceUserMapper;


    @Resource
    private RedisTemplate redisTemplate;
    //    登录
    @Override
    public CouponAdminVo login(CouponAdmin couponAdmin) {
//        将用户信息转换为json格式
//        String userJson= JSON.toJSONString(couponAdmin);
        //        获取用户的账号和密码
        String userName=couponAdmin.getUserAdmin();
        String userPassword=couponAdmin.getUserPwd();
//        首先判断值是否为空
        if(Strings.isEmpty(userName)||Strings.isEmpty(userPassword)){
            return null;
//        if(Strings.isEmpty(userJson)){
////            return null;
        }else {
//           如果不为空，判断是否存在该用户
            LambdaQueryWrapper<CouponAdmin> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(CouponAdmin::getUserAdmin,couponAdmin.getUserAdmin());
//            查询这个对象是否存在
            CouponAdmin couponAdmin1=couponAdminMapper.selectOne(queryWrapper);
//            如果该用户存在  用户名和密码进行创建token
            String token = JwtUtil.createToken(userName,userPassword);

            CouponAdminVo couponAdminVo = new CouponAdminVo();
            couponAdminVo.setUserAdmin(couponAdmin1.getUserAdmin());
            couponAdminVo.setToken(token);
            couponAdminVo.setHotelNo(couponAdmin1.getUserNo());
            couponAdminVo.setUserPower(couponAdmin1.getUserPower());
            //  获取uuid
            // String uuid= UUIDUtils.getUUID();
            //创建一个集合去接收用户信息
            List<CouponAdminVo> list=new ArrayList<>();
            //  将用户信息存放在list集合中
            list.add(couponAdminVo);

            //将数据写入redis opsForValue().set()操作的事String类型  以CouponAdmin作为key 以uuid作为value  是为了确保数据的唯一性
           // 将用户的信息存入redis缓存中  减少对数据库的IO操作   设置过期时间为7天
            redisTemplate.opsForValue().set("couponAdmin",list ,7,TimeUnit.DAYS);

            // System.out.println(redisTemplate.opsForValue().set("couponAdmin",list ,7, TimeUnit.DAYS));
            return couponAdminVo;

        }
    }


    //注册
    @Override
    public Boolean Register(CouponAdmin couponAdmin) {
        //        获取用户的账号和密码
        String userName=couponAdmin.getUserAdmin();
        String userPassword=couponAdmin.getUserPwd();
        String userTelno=couponAdmin.getUserTelno();

//        首先判断值是否为空
//        if(StringUtils.hasText(userName)||StringUtils.hasText(userPassword)){
//        if(ObjectUtils.isEmpty(userName)||ObjectUtils.isEmpty(userPassword)){
//        if(!StringUtils.hasLength(userName)||!StringUtils.hasLength(userPassword)){
        if(Strings.isEmpty(userName)||Strings.isEmpty(userPassword)||Strings.isEmpty(userTelno)){
            System.out.println("用户名或者密码为空");
        }else {
//           如果不为空，判断是否存在该用户
            LambdaQueryWrapper<CouponAdmin> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CouponAdmin::getUserAdmin, couponAdmin.getUserAdmin());
//            查询这个对象是否存在
            Integer count = couponAdminMapper.selectCount(queryWrapper);
            //如果该用户存在
            if (count > 0) {
                System.out.println("该用户已经存在！");
            }
//            如果不存在
//            CouponAdmin couponAdmin1 = new CouponAdmin();
//            couponAdmin1.setUserAdmin(userName);
//            couponAdmin1.setUserPwd(userPassword);
//            couponAdmin1.setUserNo(couponAdmin.getUserNo());
//            couponAdmin1.setUserPower(couponAdmin.getUserPower());


//            将传进来的参数 做一次添加

            Integer registerUser = couponAdminMapper.insert(couponAdmin);
            
//            System.out.println(couponAdmin1);
            System.out.println(registerUser);
//            将客服（酒店对象）做添加
            CustomerServiceUser customerServiceUser=new CustomerServiceUser();
//            使用强转将int转为String
            customerServiceUser.setUserAdmin(String.valueOf(couponAdmin.getUserNo()));
            customerServiceUser.setNickName(couponAdmin.getUserAdmin());
            customerServiceUser.setIdentity(couponAdmin.getUserPower());
            customerServiceUser.setIdentity(1);
            Integer serviceUser=customerServiceUserMapper.insert(customerServiceUser);
            System.out.println(customerServiceUser);
            return (registerUser>0 && serviceUser>0);
        }
        return false;
    }

    // 发送短信
    @Override
    public boolean sendMessage(Map<String, Object> map, String userTelno) {
        if(Strings.isEmpty(userTelno)){
            return false;
        }

        // 地域ID RAM账号的AccessKey ID  RAM账号Access Key Secret
        DefaultProfile defaultProfile=DefaultProfile.getProfile("default",
                aliyunPhoneConfig.getAccessKeyId(),aliyunPhoneConfig.getSecret());
        IAcsClient client=new DefaultAcsClient(defaultProfile);
//        设置相关固定的参数
        CommonRequest request=new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com"); //云服务(不能修改)
        request.setSysVersion("2017-05-25");//版本号(不能修改)
        request.setSysAction("SendSms");// 发送方式(不能修改)

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",aliyunPhoneConfig.getPhonenumber()); //手机号
        request.putQueryParameter("SignName",aliyunPhoneConfig.getSignname()); //申请阿里云 签名名称
        request.putQueryParameter("TemplateCode",aliyunPhoneConfig.getTemplatecode()); //申请阿里云 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map)); //验证码数据，转换json数据传递
//最终发送
        CommonResponse response = null;

        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        boolean success = response.getHttpResponse().isSuccess();
        return success;
    }

    //  手机号验证码登录
    @Override
    public CouponAdminVo  loginByCode(String userTelno, String code) {
        LambdaQueryWrapper<CouponAdmin> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(CouponAdmin::getUserTelno,userTelno);

//        查询这个对象的手机号是否存在
        CouponAdmin couponAdmin=couponAdminMapper.selectOne(queryWrapper);
        String token =JwtUtil.createToken(couponAdmin.getUserAdmin(),couponAdmin.getUserPwd());
//        String token =JwtUtil.createToken(couponAdmin.getUserTelno(),code );
//        return token;
        System.out.println(token);
//        进行封装
        CouponAdminVo couponAdminVo = new CouponAdminVo();
        couponAdminVo.setUserAdmin(couponAdmin.getUserAdmin());
        couponAdminVo.setUserPower(couponAdmin.getUserPower());
        couponAdminVo.setToken(token);
        couponAdminVo.setHotelNo(couponAdmin.getUserNo());

////        将用户的手机号和验证码进行封装   并存入Redis中 设置过期时间为60秒
//        CouponAdminVo couponAdminVo1 = new CouponAdminVo();
//        couponAdminVo.setPhone(couponAdmin.getUserTelno());
//        couponAdminVo.setCode(code);
//        redisTemplate.opsForValue().set("couponAdmin1",couponAdminVo,60,TimeUnit.SECONDS);
        return couponAdminVo;
    }
}

